
remove(list=ls())

#install.packages("pacman")
library(pacman)

p_load(here, tidyverse, ggplot2, broom, haven, modelsummary, cregg, distributional,
     sjPlot, jtools, sdamr, ggpubr, survey, xtable, interactions, viridisLite, stargazer,
     ggdist, patchwork, estimatr, margins, doBy, modelr, plyr, dplyr, tidyr)


colors2 <- c("#56B4E9", "#C5407EFF")

###LOADING DATA AND CLEANING###

df_study2 <- read_dta("data/study2_data.dta")

df_study2 <-df_study2%>% 
  mutate(res_party2= as.factor(res_party2),
         isLAB= as.factor(isLAB),
         resp_gender= as.factor(resp_gender),
         queer= as.factor(queer),
         degree= as.factor(degree),
         nonwhite= as.factor(nonwhite),
         knowparty= as.factor(knowparty),
         fourarm= as.factor(fourarm),
         IDstrength=as.factor(IDstrength),
         squeezedDV=as.factor(squeezedDV),
         partyID= as.factor(partyID),
         strongdislike=as.factor(strongdislike),
         partynegaffectcat=as.factor(partynegaffectcat),
         hud_outgroup_1=as.factor(hud_outgroup_1),
         hud_outgroup_2=as.factor(hud_outgroup_2),
         hud_outgroup_3=as.factor(hud_outgroup_3),
         hud_outgroup_4=as.factor(hud_outgroup_4),
         hud_outgroup_1a=as.numeric(hud_outgroup_1),
         hud_outgroup_2a=as.numeric(hud_outgroup_2),
         hud_outgroup_3a=as.numeric(hud_outgroup_3),
         hud_outgroup_4a=as.numeric(hud_outgroup_4),
         hero=as.factor(hero),
         recall=as.factor(avg_recall),
         profile_name=as.factor(profile_name),
         profile_surname=as.factor(profile_surname),
         profile_age=as.factor(profile_age),
         profile_job=as.factor(profile_job),
         profile_cash=as.factor(profile_cash))

colors <- c("#C5407EFF", "#56B4E9", "#C5407EFF", "#56B4E9")


###FIGURE 5###
subset_df_study2 <- df_study2[complete.cases(df_study2$partymatch), ]
mod1<- lm(partymatch~ hero, data=subset_df_study2)
summary(mod1)
subset_df_study2$predicted<-predict(mod1, subset_df_study2)


mod2<- lm(outcome_full~ hero, data=df_study2)
modelsummary(mod2, stars=TRUE)
df_study2$predicted<-predict(mod2, df_study2)

plot1<- subset_df_study2 %>%
  data_grid(hero, .model = mod1) %>%
  augment(mod1, newdata = ., se_fit = TRUE) %>%
  ggplot(aes(x = hero, fill=hero)) +
  scale_fill_manual(values = colors) +
  scale_color_manual(values = colors)+
  geom_jitter(data=subset_df_study2, aes(x=hero, y=predicted, fill=hero),
              height=.25, width=.2,size=3, alpha=.2,
              pch=21, color="grey57")+  
  theme_ggdist()+
  stat_dist_halfeye(
    aes(dist = dist_student_t(df = df.residual(mod1), mu = .fitted, sigma = .se.fit)), 
    scale = .3, position = position_nudge(x = .35))+
  geom_hline(yintercept = 0.50, linetype="dashed", colour="gray33")+
  labs(y="Pr(Project partisanship matches respondent partisanship)", x="",
       title="(Organic) projection effects",
       subtitle="N: 255 (15.4% of sample)")+
  guides(color=FALSE)+
  ylim(0,1)+
  scale_x_discrete(labels=c("0" = "Negative valence\n(villain)", "1" = "Positive valence\n(hero)"))+
  theme(legend.position = "none",
        plot.title = element_text(color="black", face=2, hjust=0),
        axis.text.x = element_text(face=2))+
  annotate("segment", x = 2.8, xend = 2.8, y = 0.27, yend = 0.58, color = "black", linetype = "dotted")+
  annotate("segment", x = 2.7, xend = 2.8, y = 0.27, yend = 0.27, color = "black", linetype = "dotted")+
  annotate("segment", x = 2.8, xend = 2.7, y = 0.58, yend = 0.58, color = "black", linetype = "dotted")+
  annotate("label", x = 2.8, y = 0.4, label = "0.34 ***", size = 3, fontface = "bold", color = "black")



plot2<- df_study2 %>%
  data_grid(hero, .model = mod2) %>%
  augment(mod2, newdata = ., se_fit = TRUE) %>%
  ggplot(aes(x = hero, fill=hero)) +
  scale_fill_manual(values = colors) +
  scale_color_manual(values = colors)+
  geom_jitter(data=df_study2, aes(x=hero, y=predicted, fill=hero),
              height=.25, width=.2,size=3, alpha=.2,
              pch=21, color="grey57")+  
  theme_ggdist()+
  stat_dist_halfeye(
    aes(dist = dist_student_t(df = df.residual(mod2), mu = .fitted, sigma = .se.fit)), 
    scale = .3, position = position_nudge(x = .35))+
  geom_hline(yintercept = 0.50, linetype="dashed", colour="gray33")+
  labs(y="", x="",
       title="(Prompted) projection effects",
       subtitle="N: 1617")+
  guides(color=FALSE)+
  ylim(0,1)+
  scale_x_discrete(labels=c("0" = "Negative valence\n(villain)", "1" = "Positive valence\n(hero)"))+
  theme(legend.position = "none",
        plot.title = element_text(color="black", face=2, hjust=0),
        axis.text.x = element_text(face=2))+
  annotate("segment", x = 2.8, xend = 2.8, y = 0.22, yend = 0.75, color = "black", linetype = "dotted")+
  annotate("segment", x = 2.8, xend = 2.7, y = 0.22, yend = 0.22, color = "black", linetype = "dotted")+
  annotate("segment", x = 2.8, xend = 2.7, y = 0.75, yend = 0.75, color = "black", linetype = "dotted")+
  annotate("label", x = 2.8, y = 0.5, label = "0.53 ***", size = 3, fontface = "bold", color = "black")



F5<- plot1+plot2
ggsave("figures_main/Figure5.png", width = 20, height = 18, units = "cm")
F5


###FIGURE 6A###
contingency_table <- table(df_study2$guessparty, df_study2$guesskids)
chi_squared_result <- chisq.test(contingency_table)
print(chi_squared_result)

n <- nrow(df_study2)
means_ci <- df_study2 %>%
  summarise(
    Mean_guessparty = mean(guessparty),
    Mean_guesskids = mean(guesskids),
    Lower_CI_guessparty = mean(guessparty) - 1.96 * sqrt(mean(guessparty) * (1 - mean(guessparty)) / n),
    Upper_CI_guessparty = mean(guessparty) + 1.96 * sqrt(mean(guessparty) * (1 - mean(guessparty)) / n),
    Lower_CI_guesskids = mean(guesskids) - 1.96 * sqrt(mean(guesskids) * (1 - mean(guesskids)) / n),
    Upper_CI_guesskids = mean(guesskids) + 1.96 * sqrt(mean(guesskids) * (1 - mean(guesskids)) / n)
  ) %>%
  pivot_longer(
    cols = starts_with("Mean_"),
    names_to = "Variable",
    values_to = "Value"
  )

F6a<- ggplot(means_ci, aes(x = Variable, y = Value, fill = Variable)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.7), show.legend = FALSE) +
  geom_errorbar(aes(ymin = ifelse(Variable == "Mean_guessparty", Lower_CI_guessparty, Lower_CI_guesskids),
                    ymax = ifelse(Variable == "Mean_guessparty", Upper_CI_guessparty, Upper_CI_guesskids)),
                width = 0.1, position = position_dodge(width = 0.7)) +
  scale_fill_manual(values = colors) +
  scale_x_discrete(labels = c("Mean_guessparty" = "Partisanship", "Mean_guesskids" = "Children")) +
  labs(title = "Pr(Responded to false recall item)",
       x = "Variable",
       y = "Mean") +
  theme_ggdist() +
  annotate("segment", x = 1, xend = 2, y = 0.2, yend = 0.2, color = "black", linetype = "dotted")+
  annotate("segment", x = 1, xend = 1, y = 0.2, yend = 0.19, color = "black", linetype = "dotted")+
  annotate("segment", x = 2, xend = 2, y = 0.2, yend = 0.19, color = "black", linetype = "dotted")+
  annotate("label", x = 1.5, y = .2, label = ".03 ***", size = 3, fontface = "bold", color = "black")+
  theme(legend.position = "none",
        plot.title = element_text(face="bold"),
        axis.text.y = element_text(face="bold"),
        axis.title.y = element_blank(),
        axis.title.x = element_blank()) +
  coord_flip()
ggsave("figures_main/Figure6a.png", width = 18, height = 12, units = "cm")
F6a


###FIGURE6b###
placebo_df <- df_study2[complete.cases(df_study2$placebo), ]
pmod1<- lm(placebo~ hero, data=placebo_df)
summary(pmod1)
placebo_df$predicted<-predict(pmod1, placebo_df)


placeboplot1<- placebo_df %>%
  data_grid(hero, .model = pmod1) %>%
  augment(pmod1, newdata = ., se_fit = TRUE) %>%
  ggplot(aes(x = hero, fill=hero)) +
  scale_fill_manual(values = colors) +
  scale_color_manual(values = colors)+
  geom_jitter(data=placebo_df, aes(x=hero, y=placebo, fill=hero),
              height=.25, width=.2,size=3, alpha=.2,
              pch=21, color="grey57")+  
  theme_ggdist()+
  stat_dist_halfeye(
    aes(dist = dist_student_t(df = df.residual(pmod1), mu = .fitted, sigma = .se.fit)), 
    scale = .3, position = position_nudge(x = .35))+
  labs(y="", x="",
       title="(Organic) projection effects",
       subtitle="N: 202 (12.2% of sample)")+
  guides(color=FALSE)+
  scale_x_discrete(labels=c("0" = "Negative valence\n(villain)", "1" = "Positive valence\n(hero)"))+
  theme(legend.position = "none",
        plot.title = element_text(color="black", face=2, hjust=0),
        axis.text.x = element_text(face=2))+
  annotate("segment", x = 1.35, xend = 2.35, y = 1.3, yend = 1.3, color = "black", linetype = "dotted")+
  annotate("segment", x = 1.35, xend = 1.35, y = 1.3, yend = 1.2, color = "black", linetype = "dotted")+
  annotate("segment", x = 2.35, xend = 2.35, y = 1.3, yend = 1.2, color = "black", linetype = "dotted")+
  annotate("label", x = 1.85, y = 1.3, label = "-.035", size = 3, fontface = "bold", color = "black")


pmod2<- lm(placebo_full~ hero, data=df_study2)
summ(pmod2)
df_study2$predicted<-predict(pmod2, df_study2)


placeboplot2<- df_study2 %>%
  data_grid(hero, .model = pmod2) %>%
  augment(pmod2, newdata = ., se_fit = TRUE) %>%
  ggplot(aes(x = hero, fill=hero)) +
  scale_fill_manual(values = colors) +
  scale_color_manual(values = colors)+
  geom_jitter(data=df_study2, aes(x=hero, y=placebo_full, fill=hero),
              height=.25, width=.2,size=3, alpha=.2,
              pch=21, color="grey57")+  
  theme_ggdist()+
  stat_dist_halfeye(
    aes(dist = dist_student_t(df = df.residual(pmod2), mu = .fitted, sigma = .se.fit)), 
    scale = .3, position = position_nudge(x = .35))+
  labs(y="", x="",
       title="(Prompted) projection effects",
       subtitle="N: 1617")+
  guides(color=FALSE)+
  scale_x_discrete(labels=c("0" = "Negative valence\n(villain)", "1" = "Positive valence\n(hero)"))+
  theme(legend.position = "none",
        plot.title = element_text(color="black", face=2, hjust=0),
        axis.text.x = element_text(face=2))+
  annotate("segment", x = 1.35, xend = 2.35, y = 1.4, yend = 1.4, color = "black", linetype = "dotted")+
  annotate("segment", x = 1.35, xend = 1.35, y = 1.4, yend = 1.3, color = "black", linetype = "dotted")+
  annotate("segment", x = 2.35, xend = 2.35, y = 1.4, yend = 1.3, color = "black", linetype = "dotted")+
  annotate("label", x = 1.85, y = 1.4, label = ".01", size = 3, fontface = "bold", color = "black")

placeboplot1+placeboplot2
ggsave("figures_main/Figure6b.png", width = 22, height = 18, units = "cm")



###FIGURE 8###

mod3<- lm(outcome_full~ fourarm, data=df_study2)
summary(mod3)
df_study2$predictedX<-predict(mod3, df_study2)

partyplot <- df_study2 %>%
  data_grid(fourarm, .model = mod3) %>%
  augment(mod3, newdata = ., se_fit = TRUE) %>%
  ggplot(aes(x = fourarm, fill=fourarm)) +
  scale_fill_manual(values = colors) +
  scale_color_manual(values = colors)+
  geom_jitter(data=df_study2, aes(x=fourarm, y=predictedX, fill=fourarm),
              height=.2, width=.25,size=3, alpha=.2,
              pch=21, color="grey57")+  
  theme_ggdist()+
  theme(plot.subtitle = element_text(face="bold"))+
  stat_dist_halfeye(
    aes(dist = dist_student_t(df = df.residual(mod3), mu = .fitted, sigma = .se.fit)), 
    scale = .3, position = position_nudge(x = .35))+
  geom_hline(yintercept = 0.50, linetype="dashed", colour="gray33")+
  labs(y="Pr(Project partisanship matches respondent partisanship)", x="Treatment condition",
       subtitle="a) Left more likely to project than the right")+
  guides(color=FALSE)+
  scale_x_discrete(labels=c("0" = "Negative valence\nConservative voter", "1" = "Positive valence\nConservative voter",
                            "2" = "Negative valence\nLabour voter", "3" = "Positive valence\nLabour voter"))+
  theme(legend.position = "none",
        plot.title = element_text(color="black", face=2, hjust=0))+
  annotate("segment", x = 1.35, xend = 2.35, y = 0.22, yend = 0.22, color = "blue2", linetype = "dotted")+
  annotate("segment", x = 2.35, xend = 2.35, y = 0.22, yend = 0.26, color = "blue2", linetype = "dotted")+
  annotate("segment", x = 1.35, xend = 1.35, y = 0.22, yend = 0.26, color = "blue2", linetype = "dotted")+
  annotate("label", x = 1.85, y = 0.22, label = "0.15 ***", size = 3, fontface = "bold", color = "blue2")+
  annotate("text", x = 1.85, y = 0.18, label = "Conservative partisans", size = 3, fontface = "bold", color = "blue2")+
  annotate("segment", x = 3.35, xend = 4.35, y = 0.99, yend = 0.99, color = "red2", linetype = "dotted")+
  annotate("segment", x = 4.35, xend = 4.35, y = 0.99, yend = 0.95, color = "red2", linetype = "dotted")+
  annotate("segment", x = 3.35, xend = 3.35, y = 0.99, yend = 0.95, color = "red2", linetype = "dotted")+
  annotate("label", x = 3.85, y = 0.99, label = "0.72 ***", size = 3, fontface = "bold", color = "red2")+
  annotate("text", x = 3.85, y = 1.03, label = "Labour partisans", size = 3, fontface = "bold", color = "red2")

modelXfull<-lm (outcome_full ~ hero*outgroupdislike, data=df_study2)
summ(modelXfull, robust=TRUE)
df_study2$predictINTfull<-predict(modelXfull, df_study2)
treat_full <- subset(df_study2, hero== 1)
control_full <- subset(df_study2, hero== 0)

predplot2 <-
  ggplot(df_study2, aes(outgroupdislike, outcome_full, group = hero, color=hero)) +
  scale_color_manual(values = c("#C5407EFF", "#56B4E9")) +
  scale_fill_manual(values = c("#C5407EFF", "#56B4E9")) +
  theme_ggdist()+
  geom_hline(yintercept = 0.50, linetype="dashed", colour="gray33")+
  stat_smooth(method = "lm_robust", fullrange = TRUE, se=TRUE) +
  geom_jitter(data=treat_full, aes(x=outgroupdislike, y=predictINTfull, fill=hero), 
              alpha=.4, height=.04, width=1.2, size=2,
              color="#56B4E9")+
  geom_jitter(data=control_full, aes(x=outgroupdislike, y=predictINTfull, fill=hero), 
              alpha=.4, height=.04, width=1.2, size=2,
              color="#C5407EFF")+
  theme(legend.position = "none")+
  xlim(0, 10)+
  ylab("Pr(Project partisanship matches respondent partisanship)")+
  xlab("(Self-reported) negative out-group affect")+
  labs(subtitle="c) Negative out-group affect determines magnitude of effect asymmetry ")+
  annotate(
    geom="label", x = 7.5, y =.58, size = 5, color="#56B4E9", fontface=2,
    label = "Slope for respondents in\npositive valence condition")+
  annotate(
    geom="label", x = 7.5, y =.43, size = 5, color="#C5407EFF", fontface=2,
    label = "Slope for respondents in\nnegative valence condition")+
  theme(plot.subtitle = element_text(face="bold"))

df_study2 <-df_study2%>% 
  mutate(outgroupdislike_normal= outgroupdislike/10)

partymean <- ddply(df_study2, "res_party2", summarise, meanx=mean(outgroupdislike_normal))
huddy_outgroupmean <- ddply(df_study2, "res_party2", summarise, meanx2=mean(huddyfactor_outgroup, na.rm = TRUE))

UKhist1<- ggplot(df_study2, aes(x=outgroupdislike_normal, fill=res_party2)) +
  geom_density(alpha=.8) +
  theme_ggdist()+
  xlim(0,1)+
  ylim(0,4.5)+
  scale_fill_manual(values = c("blue2", "red2"), labels=c("Conservatives", "Labour")) +
  scale_color_manual(values = c("blue2", "red2")) +
  geom_vline(data=partymean, aes(xintercept=meanx,  colour=res_party2),
             linetype="dashed", size=1, alpha=.5)+
  labs(y="Density", x="(Self-reported) negative out-group affect", subtitle="b) Left hold more negative affect towards out-group than vice versa")+
  theme(legend.position = "none",
        plot.subtitle = element_text(face="bold"))+
  annotate("label", x = 0, y = 3, label = "Conservatives",
           color="blue2", size=4, fontface="bold", hjust=0)+
  annotate("label", x = 0, y = 3.25, label = "Labour",
           color="red2", size=4, fontface="bold", hjust=0)


study2_party<- (partyplot+UKhist1)/predplot2
F8<- study2_party+
  plot_annotation(title = 'Study 2: Party & affect-based exploratory analyses',
                  theme = theme(plot.title = element_text(face = "bold", size=18)))

ggsave("figures_main/Figure8.png", width = 32, height = 32, units = "cm", dpi=600)
F8
